'''本页存放关键字，方便后期调用'''
import os,random,string,time,pytest
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from Config import ConfigFile
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from Method import Allure_method
class KeyLib_ui(object):
    def __init__(self,driver):
        self.driver=driver
        self.wait = WebDriverWait(self.driver, 10)
    def wait_element(self,args):
        # 强制等待某个元素出现
        try:
            # 等待元素可见
            type, element = args.split('=', 1)[0], args.split('=', 1)[1]
            self.wait.until(
                EC.visibility_of_element_located((By.XPATH, element))  # 替换为你的定位方式和元素标识符
            )
            print("元素已出现")
        except Exception as a:
            print("等待超时，元素未出现",a)
    def get_element(self,args):
        '''
        通过出传入的定位方式和元素路径获取元素
        :param args: 定位方式=元素路径
        :return: 元素
        '''
        type, element = args.split('=',1)[0], args.split('=',1)[1]
        try:
            if '$' in element:
                element,num=element.split('$',1)[0],element.split('$',1)[1]
                if type == 'id':
                    get_element=self.driver.find_elements(By.ID, element)[int(num)]
                    return get_element
                elif type == 'xpath':
                    get_element = self.driver.find_elements(By.XPATH, element)[int(num)]
                    return get_element
            else:
                if type == 'id':
                    get_element=self.driver.find_element(By.ID, element)
                    return get_element
                elif type == 'xpath':
                    get_element = self.driver.find_element(By.XPATH, element)
                    return get_element
        except Exception as e:
            Allure_method.allure_screenshot(self.driver)
            pytest.fail(f"没有找到定位元素: {args},错误为-------{e}")
    def input_text(self,*args):
        '''
        对某个元素做输入操作关键字
        :param args: 元素，输入的内容
        :return: 布尔值
        '''
        element,text=args[0].split(',',1)[0],args[0].split(',',1)[1]
        _element=self.get_element(element)
        try:
            if 'randomstr' in text:
                #生成随机字符串
                text=Method().generate_random_string(text)
            if 'randomnum' in text:
                #生成随机纯数字
                text=Method().generate_random_number(text)
            # if len(text) > 10:
            #     _element.send_keys(text[:10])
            #     _element.send_keys(text[10:])
            # else:
            #     _element.send_keys(text)
            #输入text文本
            _element.send_keys(text)
        except Exception as e:
            Allure_method.allure_screenshot(self.driver)
            pytest.fail(f'input_text:{element}元素输入文字{text}错误，错误为-----------{e}')
    def click(self, *args):
        '''
        鼠标点击元素事件
        :param args: 元素
        :return: 布尔值
        '''
        #创建 ActionChains 对象
        actions = ActionChains(self.driver)
        # 找元素
        _element = self.get_element(args[0])
        try:
            #先滚动，再点击，以防不可见的元素
            self.driver.execute_script("arguments[0].scrollIntoView();", _element)
            # time.sleep(0.3)
            _element.click()
        except Exception as e:
            Allure_method.allure_screenshot(self.driver)
            pytest.fail(f'点击元素{args[0]}出错，错误为：{e}')
    def clear(self,*args):
        '''
        输入框清空数据操作
        :param element: 元素
        :return: 布尔值
        '''
        # self.wait_element(args[0])
        _element=self.get_element(args[0])
        time.sleep(1)
        try:
            # _element.clear()   #selenium元素调用clear
            _element.send_keys(Keys.CONTROL + 'a')  #以防清理不干净 在 Windows 上全选文本
            _element.send_keys(Keys.DELETE)  # 删除选中的内容
        except Exception as e:
            Allure_method.allure_screenshot(self.driver)
            pytest.fail(f'clera清空元素：{args[0]}的text出错，错误为：------{e}')
    def should_element(self,*args):
        '''
        断言，判断元素的文本是否一致
        :param args:
        :return:
        '''
        try:
            element,should_text=args[0].split(',',1)[0],args[0].split(',',1)[1]
            _element=self.get_element(element)
            #断言文本是否在指定元素内
            if '|' in should_text:
                #分割，有多少分割夺少
                result =should_text.split('|',)
                for i in result:
                    #判断每一个是否都在
                    assert i  in _element.get_attribute("outerHTML"),f"should_element assertion failed: {should_text}内{i} 不在{_element.get_attribute('outerHTML')}.."
            else:
                assert should_text in _element.get_attribute("outerHTML"),f"should_element assertion failed: {should_text} 不在{_element.get_attribute('outerHTML')}.."
        except Exception as e:
            Allure_method.allure_screenshot(self.driver)
            pytest.fail(f"断言测试失败:捕获到异常 - {e}")
    def should_element_not(self,*args):
        try:
            element,should_text=args[0].split(',',1)[0],args[0].split(',',1)[1]
            _element=self.get_element(element)
            if '|' in should_text:
                #分割，有多少分割夺少
                result =should_text.split('|',)
                for i in result:
                    assert i not in _element.get_attribute("outerHTML"),f"should_element_not assertion failed: {should_text}中{i} 在{_element.get_attribute('outerHTML')}内."
            else:
                assert should_text not in _element.get_attribute("outerHTML"),f"should_element_not assertion failed: {should_text} 在{_element.get_attribute('outerHTML')}内."
        except Exception as e:
            Allure_method.allure_screenshot(self.driver)
            pytest.fail(f"断言测试失败:捕获到异常 - {e}")
    def should_contain(self,*args):
        '''
        断言判断是否网页里得源码包含预期
        :param args: 是否被包含的内容
        :return:
        '''
        try:
            #判断断言参数是否多个，如果多个，分割出来
            if '|' in args[0]:
                #分割，有多少分割夺少
                result =args[0].split('|',)
                for i in result:
                    #判断每一个是否都在
                    assert i  in self.driver.page_source,f"should_contain assertion failed: {args[0]} 中 {i} not in html ."
            else:
                assert args[0] in self.driver.page_source,f"should_contain assertion failed: {args[0]} not in html ."
        except Exception as e:
            # # 生成当前时间，作为png文件名
            # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
            # screenshot_path = os.path.join(os.getcwd(), 'Image', f'{current_time}.png')  # 保存截图的路径
            # self.driver.save_screenshot(screenshot_path)  # 截图
            # # 附加截图到报告
            # allure.attach.file(screenshot_path, name=current_time, attachment_type=allure.attachment_type.PNG)
            Allure_method.allure_screenshot(self.driver)
            # 断言捕捉到异常，直接用例状态失败
            pytest.fail(f"测试失败: 捕获到异常 - {e}")
    def should_contain_not(self,*args):
        '''
        断言判断是否网页里得源码不包含预期
        :param args: 是否被包含的内容
        :return:
        '''
        '''
        断言判断是否网页里得源码包含预期
        :param args: 是否被包含的内容
        :return:
        '''

        try:
            #判断断言参数是否多个，如果多个，分割出来
            if '|' in args[0]:
                #分割，有多少分割夺少
                result =args[0].split('|',)
                for i in result:
                    #判断每一个是否都不在
                    assert i  not in self.driver.page_source,f"should_contain_not assertion failed: {args[0]} 中 {i} in html ."
            else:
                assert args[0] not in self.driver.page_source,f"should_contain_not assertion failed: {args[0]} in html ."
        except Exception as e:
            #断言捕捉到异常，直接用例状态失败
            # pytest.fail(f"测试失败: 捕获到异常 - {e},")
            # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")  # 生成当前时间，作为png文件名
            # screenshot_path = os.getcwd() + '/Image/' + current_time + '.png'  # 保存截图的路劲
            # self.driver.save_screenshot(screenshot_path)  # 截图
            # allure.attach.file(screenshot_path, name=current_time, attachment_type=allure.attachment_type.PNG)
            # 生成当前时间，作为png文件名
            # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
            # screenshot_path = os.path.join(os.getcwd(), 'Image', f'{current_time}.png')  # 保存截图的路径
            # self.driver.save_screenshot(screenshot_path)  # 截图
            # # 附加截图到报告
            # allure.attach.file(screenshot_path, name=current_time, attachment_type=allure.attachment_type.PNG)
            #截图
            Allure_method.allure_screenshot(self.driver)
            # 断言捕捉到异常，直接用例状态失败
            pytest.fail(f"测试失败: 捕获到异常 - {e}")
    def time(self,num):
        time.sleep(int(num))

    def input_pay(self,paypwd=ConfigFile.paypwd):
        '''
        输入支付密码方法
        :param paypwd:
        :return:
        '''
        # paypwd=ConfigFile.paypwd
        try:
            time.sleep(0.5)
            self.driver.find_elements(By.XPATH,'//input[@class="border-input"]')[0].send_keys(paypwd[0])
            time.sleep(0.5)
            self.driver.find_elements(By.XPATH,'//input[@class="border-input"]')[1].send_keys(paypwd[1])
            time.sleep(0.5)
            self.driver.find_elements(By.XPATH,'//input[@class="border-input"]')[2].send_keys(paypwd[2])
            time.sleep(0.5)
            self.driver.find_elements(By.XPATH,'//input[@class="border-input"]')[3].send_keys(paypwd[3])
            time.sleep(0.5)
            self.driver.find_elements(By.XPATH,'//input[@class="border-input"]')[4].send_keys(paypwd[4])
            time.sleep(0.5)
            self.driver.find_elements(By.XPATH,'//input[@class="border-input"]')[5].send_keys(paypwd[5])
            time.sleep(0.5)
        except Exception as e:
            #遇到异常先截图
            Allure_method.allure_screenshot(self.driver)
            #标记结束用例
            pytest.fail(f'输入支付密码{paypwd}失败，捕捉到异常{e}')

    def roll_down(self):
        # self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # 创建 ActionChains 对象
        actions = ActionChains(self.driver)

        # 滚动到页面底部
        actions.send_keys(Keys.END).perform()









class Method(object):
    def generate_random_string(self, input_str):
        # 获取随机字符串的长度
        length = self.get_length_from_str(input_str)
        # 生成随机字符串
        letters_and_digits = string.ascii_letters + string.digits
        return ''.join(random.choice(letters_and_digits) for _ in range(length))
    def generate_random_number(self,input_str):
        # 获取随机字符串的长度
        length = self.get_length_from_str(input_str)
        # 生成随机纯数字
        # 生成纯数字随机字符串
        digits = string.digits
        return ''.join(random.choice(digits) for _ in range(length))

    def get_length_from_str(self, input_str):
        # 找到数字部分的起始位置
        i = len(input_str)
        while i > 0 and input_str[i - 1].isdigit():
            i -= 1
        # 返回数字部分的整数值作为长度
        return int(input_str[i:]) if i < len(input_str) else 0


if __name__ == '__main__':
    print(Method().generate_random_string('random15'))